/**
 * Created by Joe on 2017/7/5 0005.
 */
var Order = {
    type: {
        create: 1,
        readonly: 2,
        inventory: 3
    },
    fields: {
        selects: ["type"], //下拉框
        radios: [],//单选框
        checkboxs: [],//复选款
        textareas: [],//多行文本框
        selfDefine: [{"field": "metroLine ", "selector": "a.metro_line"}]
    },
    inventory_dataTable: "",
    order_sales_dataTable: "",
    readonly_dataTable: "",
    order_dataTable: "",
    submit: 0
};

$(document).ready(function () {
    initFormValidate();
    $('.dataTables-example').DataTable({
        "paging": false,
        "searching": false,
        "info": false,
        "ordering": false,
        "language": {
            "url": "/vendor/datatables/zh-cn.json"
        }
    });

    var inventory_dataTable = $('#DataTables_inventory').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "/vendor/datatables/zh-cn.json"
        }
    });
    Order.inventory_dataTable = inventory_dataTable;
    var order_sales_dataTable = $('#DataTables_order_sales').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "/vendor/datatables/zh-cn.json"
        }
    });
    Order.order_sales_dataTable = order_sales_dataTable;
    var readonly_dataTable = $('#DataTables_order_readonly').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "/vendor/datatables/zh-cn.json"
        }
    });
    Order.readonly_dataTable = readonly_dataTable;
    $('.btn-detail').on('click', function () {
        $("#order-detail-modal").modal("toggle");
    });
    $('.btn-detail-readonly').on('click', function () {
        $("#order-detail-modal").modal("toggle");
    });
    $('#saveInExpress').on('click', function () {
        var elements = ["trackingNo", "serialNumber"];
        Utils.clearByInputName(elements);
        $("#expressId").val("");
        $("#express_source").val("20");
        $("#DataTables_express_goodlist").DataTable().rows().remove().draw();
        $("#express-detail-modal").modal("toggle");
    });
    $('#saveOutExpress').on('click', function () {
        var elements = ["trackingNo", "serialNumber"];
        Utils.clearByInputName(elements);
        $("#expressId").val("");
        $("#express_source").val("21");
        $("#DataTables_express_goodlist").DataTable().rows().remove().draw();
        $("#express-detail-modal").modal("toggle");
    });

    $('#exampleIconifiedTabsTwo').on('click', '.express-detail-o', function () {
        requestExpressDetail($(this).attr("data"), "#DataTables_express_goodlist", Order.type.create);
    });
    $('#exampleIconifiedTabsTwo').on('click', '.express-detail-i', function () {
        requestExpressDetail($(this).attr("data"), "#DataTables_express_goodlist", Order.type.inventory);
    });
    $('#exampleIconifiedTabsTwo').on('click', '.express-detail-r', function () {
        requestExpressDetail($(this).attr("data"), "#DataTables_express_goodlist", Order.type.readonly);
    });
    $('#exampleIconifiedTabsTwo').on('click', '.btn-confirm-send', function () {
        var url = /*[[@{/orderRepair/updateAsDelivered}]]*/ '/orderRepair/updateAsDelivered';
        requestUpdateDeliveryedStatus($(this).attr("data"), url);
    });
    $('#exampleIconifiedTabsTwo').on('click', '.btn-confirm-received', function () {
        var url = /*[[@{/orderRepair/updateAsReceived}]]*/ '/orderRepair/updateAsReceived';
        requestUpdateDeliveryedStatus($(this).attr("data"), url);
    });
    $('#exampleIconifiedTabsTwo').on('click', '.btn-refresh', function () {
        location.reload();
    });
    $('.btn-refresh').on('click', function () {
        location.reload();
    });
    $('#DataTables_order_sales').on('click', ' .btn-detail-cancel', function () {
        requestCancelOrder($(this).siblings("input").val());
    });
    $('#DataTables_order_sales').on('click', ' .btn-update-amount', function () {
        $("#order-amount-form input[name='id']").val($(this).attr("data"));
        $("#order-amount-form input[name='orderNo']").val($(this).siblings("input").val());
        $("#quoted-price-modal").modal("toggle");
    });
    $('#btn-update-detail-amount').on('click', function () {
        $("#order-amount-form input[name='id']").val($("#orderId").val());
        $("#order-amount-form input[name='orderNo']").val($("#orderNo").val());
        $("#quoted-price-modal").modal("toggle");
    });
    $("#saveOrderAmount").on('click', function () {
        requestUpdateAmount();
    });
    $("#btn-query-order").on('click', function () {
        Order.order_dataTable = Order.order_sales_dataTable;
        requestQueryOrderList(Order.type.create, "#DataTables_order_sales");
    });
    $("#btn-query-order-r").on('click', function () {
        Order.order_dataTable = Order.readonly_dataTable;
        requestQueryOrderList(Order.type.readonly, "#DataTables_order_readonly");
    });
    $("#btn-query-order-i").on('click', function () {
        Order.order_dataTable = Order.inventory_dataTable;
        requestQueryOrderList(Order.type.inventory, "#DataTables_inventory");
    });
    $(".btn-preview").click(function () {
        var imageUrl = $(this).attr("data");
        Utils.preview(imageUrl);
    });

    $("#btn-update-order").click(function () {
        requestUpdate();
    });

    $("#btn-save-express").click(function () {
        if ($("#order-express-form").valid()) {
            requestSaveNew();
        }
    });

    /** delete by id **/
    $('#DataTables_express_goodlist').on('click', '.btn-delete', function () {
        //delete tr row
        var $tr = $(this).parents('tr');
        var row = $('#DataTables_express_goodlist').DataTable().row($tr);
        var url = /*[[@{/orderRepair/removeGoodsFromExpress}]]*/ '/orderRepair/removeGoodsFromExpress';
        Utils.ajaxSubmit(url + "/" + $(this).siblings("input").val(), {}, function (data) {
            if (data.result == "success") {
                row.remove().draw();
                layer.msg('公司已删除', {time: 3000, icon: 6});
            }
            if (data.result == "fail") {
                Utils.errorAlert(data.result.errorMessage);
            }
        });
    });
});

function requestCancelOrder(orderNo) {
    var url = /*[[@{/orderRepair/cancel}]]*/ '/orderRepair/cancel';
    var param = $("#order-express-form").serialize();
    Utils.ajaxSubmit(url.concat("/").concat(orderNo), param).done(function (data) {
        if (data.result == "success") {
            location.reload();
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestQueryOrderList(type, targetEle) {
    $(targetEle).DataTable().rows().remove().draw();
    var url = /*[[@{/orderRepair/findOrderList}]]*/ '/orderRepair/findOrderList';
    var params = $("#query-order-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        if (data.result == "success") {
            addOrderRow(data.content, targetEle, type);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestSaveNew() {
    var url = /*[[@{/orderRepair/saveExpress}]]*/ '/orderRepair/saveExpress';
    var param = $("#order-express-form").serialize();
    Utils.ajaxSubmit(url, param).done(function (data) {
        if (data.result == "success") {
            if (data.content != null) {
                if(data.content.updateTrackingNO==true){
                    var index = layer.confirm('数据保存成功，由于当前更改物流单号，需要刷新页面', {
                        btn: ['确定', '取消'], //按钮
                        skin: 'layui-layer-molv'
                    }, function () {
                        location.reload();
                    }, function () {
                        layer.close(index)
                        $("#expressId").value(data.content.expressId);
                        addSingleExpressGoodsRow(data.content, $("#DataTables_express_goodlist").dataTable(), Order.type.inventory);
                    });
                }else{
                    layer.msg('数据保存成功', {time: 3000, icon: 6});
                    $("#expressId").value(data.content.expressId);
                    addSingleExpressGoodsRow(data.content, $("#DataTables_express_goodlist").dataTable(), Order.type.inventory);
                }
            }else{
                layer.msg('数据保存成功', {time: 3000, icon: 6});
            }
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestUpdate() {
    var url = /*[[@{/orderRepair/updateOrder}]]*/ '/orderRepair/updateOrder';
    var param = $("#order-detail-form").serialize();
    Utils.ajaxSubmit(url, param).done(function (data) {
        if (data.result == "success") {
            layer.msg('数据更新成功', {time: 3000, icon: 6});
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestExpressDetail(id, targetEle, type) {
    var url = /*[[@{/orderRepair/findExpressDetail}]]*/ '/orderRepair/findExpressDetail';
    Utils.ajaxSubmit(url.concat("/").concat(id), {}).done(function (data) {
        if (data.result == "success") {
            Utils.clearForm("#order-express-form");
            Utils.fillInputs(data.content);
            $("#DataTables_express_goodlist").DataTable().rows().remove().draw();
            addExpressGoodsRow(data.content.goodsListDtoList, targetEle, type)
            $("#express-detail-modal").modal("toggle");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestUpdateDeliveryedStatus(id, url) {

    Utils.ajaxSubmit(url.concat("/").concat(id), {}).done(function (data) {
        if (data.result == "success") {
            // layer.msg('数据更新成功', {time: 3000, icon: 6});
            location.reload();
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

function requestUpdateAmount() {
    var url = /*[[@{/orderRepair/quotePrice}]]*/ '/orderRepair/quotePrice';
    var param = $("#order-amount-form").serialize();
    Utils.ajaxSubmit(url, param).done(function (data) {
        if (data.result == "success") {
            layer.msg('数据更新成功', {time: 3000, icon: 6});
            location.reload();
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}

/**添加table行*/
function addOrderRow(orderList, targetEle, type) {
    var datatable = $(targetEle).dataTable();
    $.each(orderList, function (k, v) {
        // console.log("addBillRow each v: ", v)
        addSingleOrderRow(v, datatable, type);
    });
    Order.order_dataTable.order([5, 'desc']).draw();
}

function addSingleOrderRow(v, datatable, type) {
    var detail_url = '', mbAmount = 0;
    if (Order.type.create == type) {
        detail_url = /*[[@{/orderRepair/findOrderDetail}]]*/ '/orderRepair/findOrderDetail';
    }
    if (Order.type.readonly == type) {
        detail_url = /*[[@{/orderRepair/findOrderReadDetail}]]*/ '/orderRepair/findOrderReadDetail';
    }
    if (Order.type.inventory == type) {
        detail_url = /*[[@{/orderRepair/findOrderInventoryDetail}]]*/ '/orderRepair/findOrderInventoryDetail';
    }
    detail_url = detail_url.concat('/').concat(v.orderNo);
    var btnRemoveEle = '<input type="hidden" value="' + v.orderNo + '"> <a class="btn btn-primary btn-detail"  href="' + detail_url + '" >查看明细</a>';

    if (Order.type.create == type && (v.status == '0' || v.status == '6' || v.status == '7' ) && v.receiveSendStatus == '3') {
        btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp; <a class="btn btn-primary btn-update-amount">报价</a>');
    }
    if (Order.type.create == type && v.status == '0') {
        btnRemoveEle = btnRemoveEle.concat('&nbsp;&nbsp;&nbsp; <a class="btn btn-danger btn-detail-cancel">取消</a>');
    }
    // console.log(v.orderExtDto);
    // console.log(v.orderExtDto == null);
    if (v.orderExtDto !== null) {
        mbAmount = v.orderExtDto.mbAmount;
    }
    datatable.fnAddData([v.orderNo, v.amount, mbAmount, v.userName, v.statusDesc, v.createAtStr, btnRemoveEle]);
}

/**添加table行*/
function addExpressGoodsRow(expressGoodsList, targetEle, type) {
    var datatable = $(targetEle).dataTable();
    $.each(expressGoodsList, function (k, v) {
        addSingleExpressGoodsRow(v, datatable, type);
    });
}

function addSingleExpressGoodsRow(v, datatable, type) {
    console.log("addSingleExpressGoodsRow type=", type, " ; v= ", v);
    if (Order.type.create == type) {
        console.log();
        datatable.fnAddData([v.trackingNo, v.goodsTitle, v.serialNumber]);
    }
    if (Order.type.readonly == type) {
        datatable.fnAddData([v.trackingNo, v.goodsTitle, v.serialNumber]);
    }
    if (Order.type.inventory == type) {
        var btnRemoveEle = "";
        if (v.status == '0') {
            btnRemoveEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-danger btn-delete">删除</a>';
        }
        datatable.fnAddData([v.trackingNo, v.goodsTitle, v.serialNumber, btnRemoveEle]);
    }
}

function initFormValidate() {

    if ($("#order-express-form").length > 0) {
        var validator = $("#order-express-form").validate({
            errorElement: "span",
            errorClass: "error-block",
            focusInvalid: true,
            rules: {
                trackingNo: {required: true, maxlength: 20},
                companyName: {required: true, maxlength: 50},
                contact: {required: true, maxlength: 20},
                contactTel: {required: true, maxlength: 20},
                address: {required: true, maxlength: 100}
            },
            messages: {
                trackingNo: {required: "必须输入快递单号", maxlength: $.validator.format("长度不能超过{0}")},
                companyName: {required: "必须输入公司名称", maxlength: $.validator.format("长度不能超过{0}")},
                contact: {required: "必须输入联系人", maxlength: $.validator.format("长度不能超过{0}")},
                contactTel: {required: "必须输入联系电话", maxlength: $.validator.format("长度不能超过{0}")},
                address: {required: "必须输入详细地址", maxlength: $.validator.format("长度不能超过{0}")}
            }
        });
    }

}
